package edison.jcr.nodetype;

import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import edison.jcr.SessionContext;
import edison.persistence.NodeDefinitionBean;
import edison.persistence.NodeTypeBean;
import edison.persistence.QueryUtils;

public class NodeDefinitionImpl extends ItemDefinitionImpl implements NodeDefinition {

	protected String[] requiredPrimaryTypeNames;
	protected String defaultPrimaryTypeName;
	protected boolean isAllowsSameNameSiblings;

	NodeDefinitionImpl(SessionContext context) {
		super(context);
	}

	NodeDefinitionImpl(SessionContext context, NodeDefinitionBean bean) {
		super(context);
		this.name = bean.getName();
		this.isAutoCreated = bean.isAutoCreated();
		this.isMandatory = bean.isMandatory();
		this.onParentVersionAction = bean.getOnParentVersionAction();
		this.isProtected = bean.isProtected();
		this.declaringNodeTypeName = bean.getDeclaringNodeType();

		this.requiredPrimaryTypeNames = bean.getRequiredPrimaryTypeNames().toArray(new String[] {});
		this.defaultPrimaryTypeName = bean.getDefaultPrimaryTypeName();
		this.isAllowsSameNameSiblings = bean.isAllowsSameNameSiblings();
	}

	public NodeType[] getRequiredPrimaryTypes() {
		NodeTypeBean[] nodeTypeBeans = QueryUtils.getNodeTypes(context.getEntityManager(), requiredPrimaryTypeNames);
		NodeType[] nodeTypes = new NodeType[nodeTypeBeans.length];
		for (int i = 0; i < nodeTypes.length; i++) {
			nodeTypes[i] = new NodeTypeImpl(context, nodeTypeBeans[i]);
		}

		return nodeTypes;
	}

	public String[] getRequiredPrimaryTypeNames() {
		return requiredPrimaryTypeNames;
	}

	public NodeType getDefaultPrimaryType() {
		NodeTypeBean nodeTypeBean = QueryUtils.getNodeType(context.getEntityManager(), defaultPrimaryTypeName);
		return new NodeTypeImpl(context, nodeTypeBean);
	}

	public String getDefaultPrimaryTypeName() {
		return defaultPrimaryTypeName;
	}

	public boolean allowsSameNameSiblings() {
		return isAllowsSameNameSiblings;
	}

}